package com.imooc.controller;

import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.net.URLEncoder;

/**
 *  1. 构造网页授权url
 *  2. 获得access token
 *  3. 获得用户基本信息
 */



//@RequestMapping("/wechat")
@Slf4j
public class WechatControllerXXXX {

    @Autowired
    private WxMpService wxMpService;

    @GetMapping("/authorize")
    //returnUrl 已经在这里定义了。***********搞清楚*****************
    public String authorize(@RequestParam("returnUrl") String returnUrl) {

        // CTRL + ALT + B  查看类的使用方法。
        // 1. 配置
        // 2.  调用方法

        String url = "http://youngpeng/natapp1.cc/sell/wechat/userInfo";

        /**oauth2buildAuthorizationUrl -- 这个方法会返回（string）以下的这些参数，可以获取来用。
         * appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect
         */

        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(returnUrl));
        return "redirectUrl" + redirectUrl;
    }

    /**
     * 编写一个接受重定向URL的页面 -- 函数
     */
    @GetMapping("/userinfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        try {

            //获取access_token
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);

        } catch (WxErrorException e) {
            //只要是错误 - 都要log 出来
            log.error("【微信网页授权】{}", e);
            throw new SellException(ResultEnum.WECHAT_MP_ERROR);
        }

        //获取用户信息
        //WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        String openId = wxMpOAuth2AccessToken.getOpenId();
        System.out.print(openId);
        System.out.print("redirect"+ returnUrl + "?openid" + openId);

        return "redirect"+ returnUrl + "?openid" + openId;

    }
}
